package com.fhao.common.security.interceptor;

import cn.hutool.core.util.StrUtil;
import com.fhao.common.core.constants.Constants;
import com.fhao.common.core.constants.HttpConstants;
import com.fhao.common.core.utils.ThreadLocalUtil;
import com.fhao.common.security.service.TokenService;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    /**
     * 从哪个服务的配置文件中读取,取决于这个bean对象交给了哪个服务的spring容器进行管理.
     * 所以此处的secret是从security微服务下的spring容器中拿到的.
     */
    @Value("${jwt.secret}")
    private String secret;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = getToken(request);
        if (StrUtil.isEmpty(token)) {
            return true;
        }
        Claims claims = tokenService.getClaims(token, secret);
        Long userId = tokenService.getUserId(claims);
        String userKey = tokenService.getUserKey(claims);
        //将当前用户的userId和userKey和存储到线程本地中, 后续无需在通过解析token获取, 直接从线程本地中拿即可.
        ThreadLocalUtil.set(Constants.USER_ID,userId);
        ThreadLocalUtil.set(Constants.USER_KEY,userKey);
        tokenService.extendToken(claims);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();//清除 ThreadLocal中的数据.
    }

    private String getToken(HttpServletRequest request) {
        String token = request.getHeader(HttpConstants.AUTHENTICATION);
        //如果token不为空, 并且token的前缀是 HttpConstants.PREFIX 则 将token的前缀去除再返回,否则直接返回.
        if(StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX,"");
        }
        return token;
    }



}
